package com.kaifamiao.dao;

import com.kaifamiao.entity.RegularFile;
import com.kaifamiao.utils.DataSourceUtils;

import org.apache.commons.dbutils.BaseResultSetHandler;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class RegularFileDao {

    private QueryRunner runner;

    public RegularFileDao(){
        super();
        // 根据DataSource创建QueryRunner实例
        runner = new QueryRunner(DataSourceUtils.getDataSource());
    }

    // 保存文件信息
    public void save(RegularFile rf){
        String sql = "INSERT INTO t_regular_files (`path`,`name`,`checksum`,`upload_time`) VALUES (?,?,?,?)";
        java.sql.Timestamp updateTime = new java.sql.Timestamp( System.currentTimeMillis() );
        ResultSetHandler<Integer> rsHandler = rs -> {
            if( rs.next() ) {
                return rs.getInt( 1 );
            }
            return null;
        };
        try {
            int id = runner.insert(sql, rsHandler, rf.getPath(), rf.getName(), rf.getChecksum(), updateTime);
            System.out.println(id);
            rf.setId(id);
        } catch ( SQLException cause ) {
            throw new RuntimeException( "保存失败" , cause);
        }
    }

    // 删除文件信息
    public void delete(Integer id){
        String sql = "DELETE FROM t_regular_files WHERE id = ?";
        try {
            runner.update(sql, id );
        } catch (SQLException cause) {
            throw new RuntimeException("删除失败", cause);
        }
    }

    // 查询所有的文件信息
    public List<RegularFile> findAll(){
        String sql = "SELECT id, name, upload_time FROM t_regular_files ORDER BY 3 DESC";
        ResultSetHandler<List<RegularFile>> rsHandler = rs -> {
            List<RegularFile> list = new ArrayList<>();
            while( rs.next() ) {
                RegularFile rf = new RegularFile();
                rf.setId( rs.getInt( "id") );
                rf.setName( rs.getString( "name" ) );
                java.sql.Timestamp ts = rs.getTimestamp( "upload_time" );
                LocalDateTime datetime = ts == null ? null : ts.toLocalDateTime();
                rf.setUploadTime( datetime );
                list.add( rf );
            }
            return list;
        };
        try {
            return runner.query( sql, rsHandler );
        } catch (SQLException cause) {
            throw new RuntimeException( "查询失败" , cause);
        }
    }

    // 查询指定文件的信息
    public RegularFile find(Integer id){
        String sql = "SELECT id, path, name, checksum FROM t_regular_files WHERE id = ? ";
        ResultSetHandler<RegularFile> rsHandler = rs -> {
            if( rs.next() ) {
                RegularFile rf = new RegularFile();
                rf.setId( rs.getInt( "id" ) );
                rf.setPath( rs.getString( "path" ) );
                rf.setName( rs.getString( "name" ) );
                rf.setChecksum( rs.getString( "checksum" ) );
                return rf;
            }
            return null;
        };
        try {
            return runner.query( sql, rsHandler, id );
        } catch (SQLException cause) {
            throw new RuntimeException("查询失败", cause);
        }
    }

    // 查询除id对应的文件信息外
    // 还有几个文件信息使用了与当前文件相同的checksum
    public int count(String checksum, Integer id){
        String sql = """
                        SELECT count(checksum) FROM t_regular_files 
                        WHERE checksum = ? AND id != ?
                     """;
        ResultSetHandler<Integer> handler = rs -> {
            if( rs.next() ) {
                return rs.getInt( 1 );
            }
            return 0;
        };
        try {
            return runner.query( sql, handler, checksum, id);
        } catch (SQLException cause) {
            throw new RuntimeException("查询失败", cause);
        }
    }
}
